import re
from urllib import request


# 断点调试
class Spider1_():
    url = 'https://www.douyu.com/directory/game/LOL'
    root_pattern = '<div class="items items01 item-data clearfix">([\s\S]*?)</div>'
    name_pattern = '</i>([\s\S]*?)</span>'
    pop_pattern = ' <span class="video-number">([\s\S]*?)</span>'

    def __fetch_content(self):
        r = request.urlopen(Spider1_.url)
        # bytes
        htmls = r.read()
        htmls = str(htmls, encoding='utf-8')
        return htmls

    '''
    正则分析
    '''

    def __analysis(self, htmls):
        root_html = re.findall(Spider1_.root_pattern, htmls)
        anchors = []
        for html in root_html:
            name = re.findall(Spider1_.name_pattern, html)
            number = re.findall(Spider1_.pop_pattern, html)
            anchor = {'name': name, 'number': number}
            anchors.append(anchor)
        return anchors

    '''
    定义去空等处理
    '''

    def __refine(self, anchors):
        l = lambda anchor: {
            'name': anchor['name'][0].strip(),
            'number': anchor['number'][0].strip()  # strip 去空格
        }
        return map(l, anchors)

    '''
    排序
    '''

    def __sort(self, anchors):
        anchors = sorted(anchors, key=self._sort_seed, reverse=True)  #
        return anchors

    '''
    排序整理
    '''

    def _sort_seed(self, anchor):
        r = re.findall('\d*', anchor['number'])
        number = float(r[0])
        if '万' in anchor['number']:
            number *= 10000
        return number

    '''
    显示格式
    '''

    def __show(self, anchors):
        for rank in range(0, len(anchors)):
            print('rank' + str(rank + 1)
                  + ' : ' + anchors[rank]['name']
                  + ' : ' + anchors[rank]['number'])

    def go(self):
        htmls = self.__fetch_content()
        anchors = self.__analysis(htmls)
        anchors = list(self.__refine(anchors))
        anchors = self.__sort(anchors)
        self.__show(anchors)


Spider1_ = Spider1_()
Spider1_.go()
